package com.awaken.content.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.Ordered;

@Configuration
public class CorsConfig {

    private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);

    // 允许的源列表
    private static final List<String> ALLOWED_ORIGINS = Arrays.asList(
        // 本地开发环境
        "http://localhost:3000",
        "http://localhost:4000",
        "http://localhost:5173",
        "http://localhost:8081",
        "http://localhost:8084",
        "http://localhost:9001",
        // 局域网IP地址
        "http://192.168.31.100",
        "http://192.168.31.100:5173",
        "http://192.168.31.123",
        "http://192.168.31.123:4000",
        // 生产环境域名
        "https://bj.aiawaken.top",
        "https://www.aibijian.com",
        "https://aibijian.com",
        "https://aiawaken.top"
    );

    @Bean
    public CorsFilter corsFilter() {
        logger.info("开始初始化跨域配置...");

        CorsConfiguration config = new CorsConfiguration();

        // 设置允许的源
        ALLOWED_ORIGINS.forEach(origin -> {
            config.addAllowedOrigin(origin);
            logger.debug("添加允许的源: {}", origin);
        });

        // 添加允许的域名模式
        config.addAllowedOriginPattern("*.aismrti.com");
        config.addAllowedOriginPattern("*.aiawaken.top");
        logger.debug("添加允许的域名模式: *.aismrti.com, *.aiawaken.top");

        // 允许凭证
        config.setAllowCredentials(true);

        // 允许的头部
        config.addAllowedHeader("*");

        // 允许的HTTP方法
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("PATCH");

        // 暴露的响应头（用于前端获取自定义响应头）
        config.addExposedHeader("*");

        // 预检请求的有效期（秒）
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        logger.info("跨域配置初始化完成");
        return new CorsFilter(source);
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        logger.info("开始注册corsFilter");
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(corsFilter());
        registration.addUrlPatterns("/*");
        registration.setName("corsFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE); // 设置为最高优先级
        logger.info("corsFilter注册完成，优先级设置为最高");
        return registration;
    }
}
